package JPetStore.web.servlet;

import JPetStore.domain.Account;
import JPetStore.domain.Cart;
import JPetStore.domain.Item;
import JPetStore.persistence.CartDao;
import JPetStore.persistence.impl.CartDaoImpl;
import JPetStore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class RemoveCartItemServlet extends HttpServlet {

    private static final String ERROR_FORM = "/WEB-INF/jsp/common/error.jsp";
    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");

        String workingItemId = req.getParameter("workingItemId");
        Item item = cart.removeItemById(workingItemId);
        try{
            Account loginAccount = (Account) session.getAttribute("loginAccount");
            CartDao cartDao = new CartDaoImpl();
            cartDao.deleteAll(loginAccount);
            cartDao.insertCart(cart.getCartItemList(),loginAccount);
        }catch (Exception e){
            e.printStackTrace();
        }

        if (item == null) {
            session.setAttribute("errorMsg", "Attempted to remove null CartItem from Cart.");
            req.getRequestDispatcher(ERROR_FORM).forward(req, resp);
        } else {
            Account loginAccount = (Account) session.getAttribute("loginAccount");
            if (loginAccount != null) {
                String username = loginAccount.getUsername();
                String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                        + req.getContextPath() + req.getServletPath() + "?" + (req.getQueryString());
                LogService logService = new LogService();
                String logInfo = logService.logInfo(new Object[]{" "}) + strBackUrl + "删除了"+item.getItemId();
                logService.insertLogInfo(username, logInfo);
            }
            req.getRequestDispatcher(CART_FORM).forward(req, resp);
        }
    }
}
